# ========= 导入基础模块 ============
from resources_base.module_base.importbase import *
# ========= 导入sqlhelper模块 =======
from resources_base.module_base import sqlhelper
from trainweb.models import Trainee


def index(request):
    return render(request, 'basic/employee.html')


def list_values(request):
    """获取所有员工信息"""
    # 接收分页信息
    page = int(request.POST.get('page'))
    limit = int(request.POST.get('limit'))
    # 定义返回数据结构
    res = {'code':0}
    # 准备SQL语句
    sql = "Select EId, Name, Gender, Birthday, Mobile, Email,Status,Employment_time, create_time from HR_Employee_Info;"
    # 准备keys
    keys = ['eid', 'name', 'gender', 'birthday', 'mobile', 'email', 'status', 'employment_time', 'create_time']
    # 获取数据
    response = sqlhelper.get_db_data_dict(sql, keys)
    # 判断获取数据是否陈宫
    if response.get('status'):
        res['count'] = len(response.get('data'))
        res['data'] = response.get('data')[(page - 1) * limit:page * limit]
    else:
        res['code'] = -1
        res['msg'] = response.get('error')
    # 直接返回
    return JsonResponse(res)


def change_employee_status(request):
    """改变员工的状态【在职、离职】"""
    # 获取传递过来的值
    eid = request.POST.get('eid')
    status = request.POST.get('status')
    # ==== 1. 修改HR_Employee_Info中的状态 ====
    sql = """
        Update HR_Employee_Info Set Status = '%s' where Eid='%s';
    """ %(status, eid)
    # 修改
    response = sqlhelper.update_db(sql)
    # 判断是否成功
    if not response.get('status'):
        return JsonResponse({'status': False, 'error': response.get('error')})
    # ==== 2. 修改Trainee中的状态 ====
    try:
        Trainee.objects.filter(eid=eid).update(onboard=status)
        return JsonResponse({'status': True})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '修改Trainee中的员工状态出现异常，具体原因：' + str(e)})